<template>
    <div class="Ploy">
        <div class="ploy-common-control">
            <el-button type="primary" icon="el-icon-plus" @click="addPloy()">{{$t('add_ploy')}}</el-button>
        </div>
        <el-table :data="tableData" style="width: 100%" stripe>
            <el-table-column prop="id" label="ID" width="50"></el-table-column>
            <el-table-column prop="name" label="机器人" width="180"></el-table-column>
            <el-table-column prop="guid" label="机器人ID" width="300"></el-table-column>
            <el-table-column width="100" prop="" label="浮动收益"></el-table-column>
            <el-table-column width="100" prop="" label="平仓收益"></el-table-column>
            <el-table-column width="100" prop="" label="工作状态"></el-table-column>
            <el-table-column width="100" prop="" label="到期状态"></el-table-column>
            <el-table-column label="操作" width="600" fixed="right">
                <template slot-scope="scope">
                    <el-button size="mini" @click="controlStart(scope.$index, scope.row)">启动</el-button>
                    <el-button size="mini" @click="controlStop(scope.$index, scope.row)">停止</el-button>
                    <el-button size="mini" @click="controlPause(scope.$index, scope.row)">暂停</el-button>
                    <el-button size="mini" @click="controlClose(scope.$index, scope.row)">释放</el-button>
                    <el-button size="mini" @click="controlEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button size="mini" @click="controlRefresh(scope.$index, scope.row)">同步</el-button>
                    <el-button size="mini" @click="controlDetail(scope.$index, scope.row)">详细</el-button>
                    <el-button size="mini" @click="controlLog(scope.$index, scope.row)">日志</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-dialog :title="detailName" :show-close="false" :visible.sync="outerVisible" v-if="outerVisible">
            <el-card shadow="never">
                <div slot="header" class="clearfix">
                    <span>全局参数</span>
                </div>
                <div class="g-p-c">
                    <p class="clearfix"><span>名称：{{detailName}}</span><span>ID：{{guid}}</span></p>
                    <p class="clearfix" v-if="!isEdit">
                        <span v-if="QuantType">手数：{{Quantity}}</span>
                        <span v-if="!QuantType">手数：{{Quantity}} %</span>

                        <span v-if="stoptype">止损：{{StopLossValue}}</span>
                        <span v-if="!stoptype">止损：{{StopLossValue}} %</span>
                        <span>止损：{{StopLossValue}}</span>
                        <span> <el-checkbox label="重复" :checked="Repeatable" disabled></el-checkbox></span>
                        <span>方向：{{LongOrShort}}</span>
                    </p>
                    <p class="clearfix" v-if="isEdit">
                        <span v-if="QuantType">手数：<el-input style="width: 50px" size="small"
                                                            v-model="Quantity"></el-input></span>
                        <span v-if="!QuantType">手数：<el-input style="width: 50px" size="small"
                                                             v-model="Quantity"></el-input> %</span>
                        <span v-if="stoptype">止损：<el-input style="width: 50px" size="small"
                                                           v-model="StopLossValue"></el-input></span>
                        <span v-if="!stoptype">止损：<el-input style="width: 50px" size="small"
                                                            v-model="StopLossValue"></el-input> %</span>
                        <span> <el-checkbox label="重复" :checked="Repeatable" v-model="Repeatable"></el-checkbox></span>
                        <span>方向：
                            <el-radio-group v-model="LongOrShortValue">
                                <el-radio :label=null>多空</el-radio>
                                <el-radio :label=false>做空</el-radio>
                                <el-radio :label=true>做多</el-radio>
                           </el-radio-group>
                        </span>
                    </p>
                </div>
            </el-card>
            <el-tabs v-model="activeName" @tab-click="tabClickEvent">
                <el-tab-pane :label="$t('ploy_userParam_tit')" name="userParam">
                    <el-table :data="userParamData" style="width: 100%">
                        <el-table-column prop="key" label="参数" width="180"></el-table-column>
                        <el-table-column prop="Type" label="类型"></el-table-column>
                        <el-table-column prop="Value" v-if="!isEdit" label="参数值"></el-table-column>
                        <el-table-column label="参数值" v-if="isEdit">
                            <template slot-scope="scope">
                                <i class="el-icon-edit-outline" @click="editParam(scope.$index, userParamData)"></i>
                                <span style="margin-left: 2px">{{ scope.row.Value }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="Description" label="参数描述"></el-table-column>
                    </el-table>
                </el-tab-pane>
                <el-tab-pane :label="$t('ploy_userExchange_tit')" name="userExchange">
                    <el-button type="primary" v-if="isEdit" @click="exchangeAdd()" size="mini">添加</el-button>
                    <el-table :data="userExchangeData" style="width: 100%">
                        <el-table-column prop="exchange_name" label="交易所"></el-table-column>
                        <el-table-column prop="symbol" label="交易对"></el-table-column>
                        <el-table-column prop="period" label="周期"></el-table-column>
                        <el-table-column v-if="isEdit" label="操作" width="100" fixed="right">
                            <template slot-scope="scope">
                                <el-button size="mini" @click="exchangeDelete(scope.$index, scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>

                </el-tab-pane>
            </el-tabs>
            <el-dialog
                    :show-close="false"
                    :title="$t('ploy_modify_tit')"
                    :visible.sync="innerVisible"
                    width="30%"
                    append-to-body>
                <span v-if="modifyType=='number' || modifyType=='string'"><el-input v-model="modifyTypeValue"
                                                                                    :placeholder="$t('ploy_modify_placeholder')"></el-input></span>
                <span v-if="modifyType=='bool'"><el-checkbox
                        v-model="modifyTypeValue">{{$t('ploy_modify_type')}}</el-checkbox></span>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="innerVisible = false">{{$t('btn_cancel')}}</el-button>
                    <el-button type="primary" @click="btnSubmitModify(modifyTypeIndex)">{{$t('btn_submit')}}</el-button>
               </span>
            </el-dialog>
            <el-dialog
                    :show-close="false"
                    :title="$t('ploy_modify_tit01')"
                    :visible.sync="innerVisibleExchange"
                    width="30%"
                    append-to-body>
                <el-form :inline="true" :model="formExchange">
                    <el-form-item label="">
                        <el-select style="width: 130px" @change="selectExchange()" v-model="formExchange.ExchangeName"
                                   placeholder="交易所">
                            <el-option v-for="item in ExchangeIDAll" :key="item.id" :label="item.name"
                                       :value="item.name"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="">
                        <el-select style="width: 130px" @change="selectSymbol()" v-model="formExchange.Symbol"
                                   placeholder="交易对">
                            <el-option v-for="item in SymbolAll" :key="item.id" :label="item.symbol"
                                       :value="item.symbol"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="">
                        <el-select style="width: 130px" v-model="formExchange.Period" placeholder="周期">
                            <el-option v-for="item in PeriodAll" :key="item.id" :label="item.value"
                                       :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                        <el-button @click="innerVisibleExchange = false">{{$t('btn_cancel')}}</el-button>
                        <el-button type="primary" @click="btnSubmitExchangeModify()">{{$t('btn_submit')}}</el-button>
                   </span>
            </el-dialog>

            <div slot="footer" class="dialog-footer">
                <el-button @click="outerVisible = false">{{$t('btn_cancel')}}</el-button>
                <el-button v-if="isEdit" type="primary" @click="btnSubmitPush()">{{$t('btn_submit')}}</el-button>
            </div>
        </el-dialog>
        <el-dialog :title="$t('add_ploy')" :visible.sync="addPloyDialog">
            <el-form ref="form" :model="addPloyform" label-width="80px">
                <el-form-item :label="$t('ploy_select')">
                    <el-select v-model="addPloyform.guid" :placeholder="$t('ploy_select_placeholder')">
                        <el-option
                                v-for="item in ployData"
                                :key="item.id"
                                :value="item.guid"
                                :label="item.name">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item :label="$t('ploy_name')">
                    <el-input v-model="addPloyform.title"></el-input>
                </el-form-item>
                <el-form-item :label="$t('ploy_remark')">
                    <el-input type="textarea" v-model="addPloyform.desc"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="addPloyCreate()">{{$t('ploy_create')}}</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
        <el-dialog title="日志详细" :visible.sync="logVisible">
            <el-table border :data="logData.slice((currentPage-1)*pageSize,currentPage*pageSize)">
                <el-table-column type="expand">
                    <template slot-scope="props">
                        <el-form label-position="left" inline class="table-expand">
                            <el-form-item v-for="(item,indexMark) in props.row.data" :key="indexMark">
                                <label>{{indexMark}}</label>
                                <span>{{ item}}</span>
                            </el-form-item>
                        </el-form>
                    </template>
                </el-table-column>
                <el-table-column type="index" label="id"></el-table-column>
                <el-table-column prop="DateTime" label="DateTime"></el-table-column>
                <el-table-column prop="StrategyID" label="StrategyID"></el-table-column>
                <el-table-column prop="ExchangeID" label="ExchangeID"></el-table-column>
                <el-table-column prop="Symbol" label="Symbol"></el-table-column>
                <el-table-column prop="DataType" label="DataType"></el-table-column>
                <el-table-column prop="CallingClass" label="CallingClass"></el-table-column>
                <el-table-column prop="CallingMethod" label="CallingMethod"></el-table-column>
            </el-table>
            <el-pagination
                    :page-size="pageSize"
                    @current-change="handleCurrentChange"
                    layout="prev, pager, next"
                    :total=pageTotal>
            </el-pagination>
        </el-dialog>
    </div>
</template>

<script>
    export default {
        name: "Ploy",
        inject: ['reload'],
        data() {
            return {
                tableData: [],
                outerVisible: false,
                innerVisible: false,
                innerVisibleExchange: false,
                activeName: "userParam",
                userParamData: [],
                userExchangeData: [],
                isEdit: false,
                addPloyDialog: false,
                addPloyform: {
                    guid: "",
                    title: "",
                    desc: ""
                },
                ployData: [],
                Quantity: "",
                Repeatable: "",
                StopLossValue: "",
                LongOrShort: "",
                detailName: "",
                guid: "",
                id: "",
                rowData: "",
                sourceData: "",
                SpecialParamsInit: "",//最初的数据基本参数元素
                modifyType: "",//修改参数的类型
                modifyTypeIndex: "",//修改参数的table的下标
                modifyTypeValue: '',//修改参数的值
                nowEditData: "",//当前编辑的值
                formExchange: {
                    ExchangeName: '',
                    Symbol: '',
                    Period: '',
                },
                ExchangeIDAll: [],
                SymbolAll: [],
                PeriodAll: [
                    {"id": '0', "value": "1m"},
                    {"id": '1', "value": "5m"},
                    {"id": '2', "value": "15m"}
                ],
                QuantType: "",
                stoptype: "",
                LongOrShortValue: Object,
                logVisible: false,
                logData: [],
                pageSize: 10,
                pageTotal: 0,
                currentPage: 1
            };
        },
        mounted() {
            this.getUserPloy();
        },
        created() {
            // this.$eventHub.$on('auth', (res)=>{
            //     if(res){
            //         this.webSocketToken=res.token;
            //     }
            // })

            this.$eventHub.$on('start', (res) => {
                if (res) {
                    console.log("回显");
                    console.log(res);
                }
            })
        },
        methods: {
            controlClose(index, row) {//释放
                this.deletePloy(row.id);
            },
            controlEdit(index, row) {//编辑
                this.isEdit = true;
                this.detailOrEditShow(row);
            },
            controlDetail(index, row) {//详细
                this.isEdit = false;
                this.detailOrEditShow(row);
            },
            controlStart(index, row) {//启动start
                this.sendWebSocket("start", row.guid, JSON.parse(row.source));
            },
            controlStop(index, row) {//停止stop
                this.sendWebSocket("stop", row.guid, null);
            },
            controlRefresh(index, row) {//同步status
                this.sendWebSocket("status", row.guid, null);
            },
            controlPause(index, row) {//暂停suspend
                this.sendWebSocket("suspend", row.guid, null);
            },
            controlLog(index, row) {//查看日志
                this.logVisible = true;
                this.getLogData(row.id);
            },
            exchangeAdd() {//添加交易对参数
                this.getExchangePlatform();
                this.innerVisibleExchange = true;
                this.formExchange.ExchangeName = "";
                this.formExchange.Symbol = "";
                this.formExchange.Period = "";
            },
            btnSubmitExchangeModify() {//确认修改
                this.createExchange(this.formExchange.ExchangeName, this.formExchange.Symbol, this.formExchange.Period);
            },
            exchangeDelete(index, row) {
                this.deleteStartegyInstrument(row.id, index);
            },
            tabClickEvent(targetName) {
                if (targetName.name == "userExchange") {
                    //todo
                }
            },
            sendWebSocket(op, strategyid, data) {
                let token = this.getWebSocketToken();
                let username = this.getUserName();
                if (!token) {
                    this.$message.error("用户的token丢失，请重写登录！");
                    return;
                }
                if (!strategyid) {
                    this.$message.error("该策略id不存在，请重写登录！");
                    return;
                }
                if (!username) {
                    this.$message.error("用户名不存在，请重写登录！");
                    return;
                }
                //console.log(data);
                let param = {
                    "op": op,
                    "token": this.getWebSocketToken(),
                    "userid": this.getUserName(),
                    "strategyid": strategyid,
                    "data": data
                };
                if (this.$webSocket.readyState != 1) {
                    //重复连接多次数据
                    this.$webSocket = new WebSocket("ws://52.77.238.82:10112/StrategyControl");
                    return;
                }
                console.log(param);
                // var test=JSON.stringify(param);
                this.$webSocket.send(JSON.stringify(param));
            },
            detailOrEditShow(row) {
                if (row.source && row.source != undefined) {
                    this.outerVisible = true;
                    this.detailName = row.name;
                    this.guid = row.guid;
                    let sourceData = JSON.parse(row.source || {});
                    if (sourceData == null) {
                        this.$message.error(this.$t('ploy_view_error'));
                        return;
                    }
                    this.sourceData = sourceData;
                    this.rowData = row;
                    this.id = row.id;
                    this.getStartegyInstrument(this.id);//获取交易对配置
                    this.userParamData = [];
                    this.SpecialParamsInit = sourceData.SpecialParams;
                    for (var index in sourceData.SpecialParams) {
                        sourceData.SpecialParams[index]['key'] = index;
                        this.userParamData.push(sourceData.SpecialParams[index]);
                    }
                    this.QuantType = sourceData.QuantType;
                    this.Quantity = sourceData.QuantType ? sourceData.Quantity : sourceData.Quantity * 100;
                    this.stoptype = sourceData.stoptype;
                    this.StopLossValue = sourceData.stoptype ? sourceData.StopLossValue : sourceData.StopLossValue * 100;
                    this.Repeatable = sourceData.Repeatable;
                    this.LongOrShortValue = sourceData.LongOrShort;
                    if (sourceData.LongOrShort == null) {
                        this.LongOrShort = this.$t('ploy_LongOrShort_1');
                    } else if (sourceData.LongOrShort == false) {
                        this.LongOrShort = this.$t('ploy_LongOrShort_2');
                    } else if (sourceData.LongOrShort == true) {
                        this.LongOrShort = this.$t('ploy_LongOrShort_3');
                    }
                } else {
                    this.$message.error(this.$t('ploy_view_error'));
                    return;
                }
            },
            addPloy() {//添加策略
                this.addPloyDialog = true;
                this.getStrategy();
            },
            addPloyCreate() {//立即创建
                if (!this.addPloyform.guid) {
                    this.$message.error(this.$t('select_ploy_msg'));
                    return;
                }
                this.createPloy(this.addPloyform);
            },
            editParam(index, data) {
                this.nowEditData = data;
                this.modifyTypeIndex = index;
                this.innerVisible = true;
                this.modifyTypeValue = data[index]['Value'];
                this.openInnerDialog(data[index]['Type']);
            },
            openInnerDialog(type) {//打开内部修改窗口的类型
                this.modifyType = type;
            },
            btnSubmitPush() {//确定提交数据
                if (this.nowEditData) {
                    let tempData = this.tool_cloneObj(this.nowEditData);
                    var $arr = {};
                    for (var i in tempData) {
                        $arr[tempData[i].key] = tempData[i];
                        delete tempData[i].key
                    }
                    this.sourceData.SpecialParams = $arr;
                } else {
                    this.sourceData.SpecialParams = this.SpecialParamsInit;
                }
                this.sourceData.Repeatable = this.Repeatable;
                this.sourceData.LongOrShort = this.LongOrShortValue;
                this.sourceData.StopLossValue = this.stoptype ? this.StopLossValue : this.StopLossValue / 100;
                this.sourceData.Quantity = this.QuantType ? this.Quantity : this.Quantity / 100;
                this.rowData.source = JSON.stringify(this.sourceData);
                this.updatePloy(this.id, JSON.stringify(this.sourceData));
            },
            btnSubmitModify(index) {//确定修改
                if (this.modifyType == "number") {
                    if (!this.tool_is_decimal(this.modifyTypeValue)) {
                        this.$message.error(this.$t('ploy_modify_type_num_msg'));
                        return;
                    }
                } else if (this.modifyType == "string") {
                    if (this.tool_is_null(this.modifyTypeValue)) {
                        this.$message.error(this.$t('ploy_modify_type_num_msg'));
                        return;
                    }
                } else if (this.modifyType == "bool") {
                    this.modifyTypeValue = this.modifyTypeValue ? this.modifyTypeValue : false;
                }
                this.nowEditData[index]['Value'] = this.modifyTypeValue;
                this.userParamData = this.nowEditData;
                this.innerVisible = false;
            },
            getUserPloy(guid = "") {
                let $url = this.USER_STRATEGY;
                // if(guid){
                //     $url=this.USER_STRATEGY+"/"+guid;
                // }
                this.axios
                    .get($url)
                    .then(res => {
                        if (res.data.status == 'success') {
                            console.log(res.data.data);
                            this.tableData = res.data.data;
                        } else {
                            this.$message({message: res.data.msg});
                        }
                    })
                    .catch(res => {

                    });
            },
            getLogData(id) {
                this.axios
                    .get(this.STRATEGY_LOG_NEW + "/" + id)
                    .then(res => {
                        if (res.data.status == 'success') {
                            this.logData = res.data.data;
                            this.pageTotal = this.logData.length;
                        } else {
                            this.$message({message: res.data.msg});
                        }
                    })
                    .catch(res => {

                    });
            },
            selectExchange() {
                this.SymbolAll = [];
                this.formExchange.Symbol = "";
                this.formExchange.Period = "";
                this.getExchangeSymbolList(this.formExchange.ExchangeName);
            },
            selectSymbol() {
                this.formExchange.Period = "";
            },
            getExchangePlatform() {
                this.axios
                    .get(this.EXCHANGE)
                    .then(res => {
                        if (res.data.status == 'success') {
                            console.log(res.data.data);
                            this.ExchangeIDAll = res.data.data;
                        } else {
                            this.$message({message: res.data.msg});
                        }
                    })
                    .catch(res => {

                    });
            },
            getExchangeSymbolList(exchangeName) {
                this.axios
                    .get(this.EXCHANGE_SYMBOL_LIST + exchangeName)
                    .then(res => {
                        if (res.data.status == 'success') {
                            this.SymbolAll = res.data.data
                        } else {
                            this.$message({message: res.data.msg});
                        }
                    })
                    .catch(res => {

                    });
            },
            createExchange(exchangeName, symbol, period) {//创建交易对
                let data = {
                    strategy_id: this.id,
                    exchange_name: exchangeName,
                    symbol: symbol,
                    period: period
                }
                this.axios
                    .post(this.USER_STRATEGY_INSTRUMENT, data)
                    .then(res => {
                        if (res.data.status == 'success') {
                            this.SymbolAll = res.data.data;
                            this.innerVisibleExchange = false;
                            this.getStartegyInstrument(this.id);
                        } else {
                            this.$message({message: res.data.msg});
                        }
                    })
                    .catch(res => {

                    });
            },
            getStartegyInstrument(id) {
                this.axios
                    .get(this.USER_STRATEGY_INSTRUMENT + "/" + id)
                    .then(res => {
                        if (res.data.status == 'success') {
                            this.userExchangeData = res.data.data;
                        }
                    })
                    .catch(res => {

                    });
            },
            deleteStartegyInstrument(id, rowid) {
                this.axios
                    .delete(this.USER_STRATEGY_INSTRUMENT + "/" + id)
                    .then(res => {
                        if (res.data.status == 'success') {
                            this.userExchangeData.splice(rowid, 1);
                        } else {
                            this.$message({message: res.data.msg});
                        }
                    })
                    .catch(res => {

                    });
            },
            handleCurrentChange(val) {
                this.currentPage = val;
            },
            deletePloy(id) {
                this.axios
                    .delete(this.USER_STRATEGY + "/" + id)
                    .then(res => {
                        if (res.data.status == 'success') {
                            this.reload();
                            this.$message({message: this.$t('ploy_close_success'), type: 'success'});
                        } else {
                            this.$message({message: res.data.msg});
                        }
                    })
                    .catch(res => {

                    });
            },
            updatePloy(id, sourceData) {
                if (!id) {
                    this.$message.error("策略id丢失，请刷新后重试!");
                    return;
                }
                let data = {"source": sourceData, "input_params": '1'};
                this.axios
                    .put(this.USER_STRATEGY + "/" + id, data)
                    .then(res => {
                        if (res.data.status == 'success') {
                            this.reload();
                            this.outerVisible = false;
                            this.$message({message: this.$t('ploy_modify_change'), type: 'success'});
                        } else {
                            this.$message({message: res.data.msg});
                        }
                    })
                    .catch(res => {

                    });
            },
            getStrategy() {
                this.axios
                    .get(this.STRATEGY)
                    .then(res => {
                        if (res.data.status == 'success') {
                            this.ployData = res.data.data;
                        } else {
                            this.$message({message: res.data.msg});
                        }
                    })
                    .catch(res => {

                    });
            },
            createPloy(obj) {
                let param = {"name": obj.title, "desc": obj.desc, "strategy_guid": obj.guid};
                this.axios
                    .post(this.USER_STRATEGY, param)
                    .then(res => {
                        if (res.data.status == 'success') {
                            this.addPloyDialog = false;
                            this.reload();
                            this.$message({message: this.$t('add_ploy_success'), type: 'success'});
                        } else {
                            this.$message({message: res.data.msg});
                        }
                    })
                    .catch(res => {

                    });
            }

        },
        beforeDestroy() {
            // this.$eventHub.$off('webSocketError');
            // this.$eventHub.$off('webSocketInit')
        },
    }
</script>

<style scoped lang="scss">
    .clearfix {
        clear: both;
    }

    .ploy-common-control {
        position: fixed;
        z-index: 100;
        top: 60px;
        width: 100%;
        background: #fff;
        padding: 5px 0px;
    }

    .g-p-c p {
        line-height: 30px;
        span {
            padding: 20px;
        }
    }
    .Ploy .el-form--inline .el-form-item{
        width: 44%;margin-bottom: 0px;
    }
    .Ploy .el-form-item__content label{
        color: #99a9bf !important; padding-right: 20px;
    }
</style>
